package com.pl.controller;

import com.pl.config.ThreadPoolConfig;
import com.pl.handler.ThreadConsumer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 测试
 *
 * @author shent
 */
@RestController
@RequestMapping("test")
public class TestController {
    @Autowired
    ThreadConsumer threadConsumer;
    @Autowired
    ThreadPoolConfig threadPoolConfig;

    @GetMapping("thread")
    public String threadTest() {
        threadConsumer.myThread();
        return "ok";
    }

    @GetMapping("thread1")
    public String threadTest1() throws ExecutionException, InterruptedException {
        Future future = threadConsumer.myThread1();
        while (true) {
            if (future.isDone()) {
                System.out.println("result from asynchronous process - " + future.get());
                break;
            }
            System.out.println("continue doing something else.");
            Thread.sleep(1000);
        }
        return future.get() + "";
    }

    @GetMapping("show")
    public String show() {
        ThreadPoolTaskExecutor executor = threadPoolConfig.myThreadPool();
        ThreadPoolExecutor threadPoolExecutor = executor.getThreadPoolExecutor();
        String result = "活动线程数量:" + threadPoolExecutor.getActiveCount() + "\n" +
                "已完成的任务数:" + threadPoolExecutor.getCompletedTaskCount() + "\n" +
                "线程池已执行与未执行的任务总数:" + threadPoolExecutor.getTaskCount();
        System.out.println(result);
        return result;
    }

}
